<Serializable()> Class Firmware
    Public m_data() As Byte = Nothing

    Private m_progress As Integer = 0
    Private m_message As String = ""
    Public Event Progress(ByVal sender As Object, ByVal e As Threads.BikiThread_Args)
    Public Event Message(ByVal sender As Object, ByVal e As Threads.BikiThread_Args)

    Private bgw As System.ComponentModel.BackgroundWorker
    Private eventArgs As System.ComponentModel.DoWorkEventArgs

    Protected Sub OnProgress(ByVal progress As Integer)
        ' A file was found. Increment the counter,
        ' then raise the event indicating that the file was found.
        ' Note that RaiseEvent is synchronous: You're not
        ' going any further until the event is handled by all
        ' listeners.
        m_progress = progress
        RaiseEvent Progress(Me, New Threads.BikiThread_Args(m_progress, m_message))
    End Sub

    Protected Sub OnMessage(ByVal Message As String)
        ' A file was found. Increment the counter,
        ' then raise the event indicating that the file was found.
        ' Note that RaiseEvent is synchronous: You're not
        ' going any further until the event is handled by all
        ' listeners.
        m_message = Message
        RaiseEvent Message(Me, New BikiRom_UpArgs(m_progress, m_message))
    End Sub
    Public Sub Execute( _
             ByVal backGroundWorker As System.ComponentModel.BackgroundWorker, _
             ByVal e As System.ComponentModel.DoWorkEventArgs)

        ' Store the reference to the BackgroundWorker and the
        ' DoWorkEventArgs objects:
        bgw = backGroundWorker
        eventArgs = e
        OnMessage("Firmware Updating started...")
        ' Search for matching files.
        Debug.Print("before ANY status calls!")
        Me.BikiRom_BootloaderUpload()
        Close_BikiRom()
    End Sub
    Sub New(ByRef data() As Byte)
        dataLoad(data)
    End Sub

    Public Sub dataLoad(ByRef Data_() As Byte)
        m_data = Data_
    End Sub
    Private Sub bootReset()
        FT_SetRts(lngHandle)
        Threading.Thread.Sleep(20)
        FT_SetDtr(lngHandle)
        Threading.Thread.Sleep(20)
        FT_ClrDtr(lngHandle)
        Threading.Thread.Sleep(20)
    End Sub
    Private Sub bootLoad()
        Threading.Thread.Sleep(20)
        FT_ClrRts(lngHandle)
        Threading.Thread.Sleep(20)
        FT_SetDtr(lngHandle)
        Threading.Thread.Sleep(20)
        FT_ClrDtr(lngHandle)
        'Threading.Thread.Sleep(20)
    End Sub
    Private Function BikiRom_BootloaderUpload() As Boolean
        Dim f_packetSize As Integer = 256 'Val(txPacket.Text)
        Dim f_retBytes(0 To 20) As Byte
        Dim f_pageData(0 To f_packetSize + 1) As Byte
        Dim f_page(0 To 1) As Byte
        Dim s_error As Integer
        Dim s_crc As Integer
        Dim f_Crc As Integer
        f_Crc = f_packetSize + 1
        Dim f_returnBytes(0 To 20) As Byte

        Dim f_pageTwo(0 To f_packetSize + 1) As Byte
        Dim f_pageThree(0 To f_packetSize + 2) As Byte
        'Try
        'If lngHandle = 0 Then BikiRom_connect()
        If BikiRom_connect() Then
            BikiRom_SetTimeoutHigh(False)
            Dim s_blEr As Integer = 0
            Dim f_bytes() As Byte
            Dim f_count As Integer
bl:
            Me.bootLoad()
            Threading.Thread.Sleep(s_blEr)
            f_bytes = usb_read(f_count)
            If f_count = 0 Then
                s_blEr += 1
                If s_blEr >= 100 Then Return False : Exit Function
                GoTo bl
            End If
            Debug.Print("past the BB checking after wait of " & s_blEr & "ms")
            
            f_pageData(0) = 223
            f_pageTwo(0) = 223
            f_pageThree(0) = 223
            Dim f_firstByte() As Byte = {223, m_data(0)}
            Dim f_sendLength As Integer = f_packetSize + 1
            'If f_bytes(0) = 187 Then
            Threading.Thread.Sleep(100)
            OnMessage("Firmware.... Sync OK ")
            If f_bytes(0) = 187 Or f_bytes(0) = 185 Or f_bytes(0) = 177 Then
                If BikiRom_sendCmdd(f_firstByte, f_retBytes, 2, 1) Then
                    If f_retBytes(0) = 223 Then
                        OnMessage("Firmware..... Update Starting")
                        For i As Integer = 1 To UBound(m_data) Step (f_packetSize * 3)
                            array_copy(m_data, i, f_pageData, 1, f_packetSize)
                            array_copy(m_data, i + f_packetSize, f_pageTwo, 1, f_packetSize)
                            array_copy(m_data, i + (f_packetSize * 2), f_pageThree, 1, f_packetSize)
                            s_crc = 0
                            For d As Integer = 1 To (f_packetSize)
                                s_crc += CByte(f_pageData(d))
                            Next
                            For d As Integer = 1 To (f_packetSize)
                                s_crc += CByte(f_pageTwo(d))
                            Next
                            For d As Integer = 1 To (f_packetSize)
                                s_crc += CByte(f_pageThree(d))
                            Next
                            f_pageThree(f_packetSize + 1) = LOBYTE(s_crc)
reSend:

                            If BikiRom_sendCmdd(f_pageData, f_retBytes, f_packetSize + 1, 1) Then
                                Debug.Print("Past 1st packet " & i)
                                If BikiRom_sendCmdd(f_pageTwo, f_retBytes, f_packetSize + 1, 1) Then
                                    Debug.Print("Past 2nd packet " & i)
                                    If BikiRom_sendCmdd(f_pageThree, f_retBytes, f_packetSize + 2, 1) = False Then
                                        OnMessage("Firmware... Updating Failed")
                                        Return False
                                        Exit Function
                                    Else
                                        If f_retBytes(0) <> 223 Then
                                            OnMessage("Firmware... CRC error " & i)
                                            s_error = s_error + 1
                                            If s_error >= 30 Then
                                                Return False
                                                OnMessage("Firmware... Updating Failed")
                                                Exit Function
                                            End If
                                            GoTo reSend
                                        Else
                                            Debug.Print("Past 3rd packet AOK " & i)
                                        End If
                                    End If
                                    ' Exit Function
                                    If (i Mod 1024) = 0 Then
                                        OnProgress(((i / UBound(m_data)) * 100))
                                    End If
                                Else
                                    Debug.Print("Error sending packet 2", "ERROR")
                                End If
                            Else
                                Debug.Print("Error sending packet 1", "ERROR")
                            End If
                        Next
                    Else
                        GoTo bl
                        'Debug.Print("Error from initial seed byte return.. ie no return", "ERROR")
                    End If
                Else
                    s_blEr += 1
                    If s_blEr >= 100 Then Return False : Exit Function
                    GoTo bl
                End If
            Else
                s_blEr += 1
                If s_blEr >= 100 Then Return False : Exit Function
                GoTo bl
            End If
            Dim cmd() As Byte = cv_BytesFromHex("FF")
            If BikiRom_sendCmdd(cmd, f_retBytes, 1, 1) Then
                m_message = "Firmware Update 100% OK"
                OnProgress(100)
                Return True
            Else
                OnProgress(0)
                OnMessage("Firmware Updating Failed")
                Return False
            End If

            bootReset()
        Else
            OnMessage("Firmware Updating Failed. Could Not Connect")
        End If
        'Catch ex As Exception
        'OnMessage(Err.Description)
        'End Try
    End Function
End Class
